package booking.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import booking.misc.Airport;
import booking.misc.Booking;
import booking.misc.DBConnectionData;
import booking.misc.Flight;
public class BookingWindow extends JFrame implements ActionListener {
    private static final String ADD = "add";
    private static final String UPDATE = "update";
    private static final String REMOVE = "remove";
    private BookingModel bookingModel;
    JTable table;
    private JButton updateBtn;
    private JButton removeBtn;
    // - Konstruktor som skapar GUI't -------------------------------------
    public BookingWindow() {
  
    	bookingModel = new BookingModel();

    	Vector<Booking> Bookings = loadBookings();
    	
    	bookingModel.setBookings(Bookings);
        
        table = new JTable(bookingModel);
        table.setPreferredScrollableViewportSize(new Dimension(450, 100));
        table.getColumnModel().getColumn(0).setPreferredWidth(25);
        table.getColumnModel().getColumn(1).setPreferredWidth(170);
        table.getColumnModel().getColumn(2).setPreferredWidth(150);
        table.getColumnModel().getColumn(3).setPreferredWidth(200);
        table.getColumnModel().getColumn(4).setPreferredWidth(130);
        
        JScrollPane sp = new JScrollPane(table);
        add(sp, BorderLayout.CENTER);
        JPanel bottomPnl = new JPanel(new FlowLayout());
        add(bottomPnl, BorderLayout.PAGE_END);
        
        JButton btn = new JButton("Search");
        btn.addActionListener(this);
        btn.setActionCommand(ADD);
        bottomPnl.add(btn);
        
//        updateBtn = new JButton("Update");
//        updateBtn.addActionListener(this);
//        updateBtn.setActionCommand(UPDATE);
//        bottomPnl.add(updateBtn);
        
        removeBtn = new JButton("Unbook");
        removeBtn.addActionListener(this);
        removeBtn.setActionCommand(REMOVE);
        bottomPnl.add(removeBtn);
        
        setTitle("My Bookings");
        setLocationRelativeTo(null);
        pack();
    }
    
 // -- Laddar in samtliga album och returnerar dem i en vector
    private Vector<Booking> loadBookings() {
        Vector<Booking> vec = new Vector<Booking>();
        try (Connection conn = DBConnectionData.getConnection()) {
        	String sql = "SELECT flights.*,airports.City AS Depature_City, airports_2.City AS Arrival_City, user_ID, flight_ID FROM flights INNER JOIN airports ON flights.depatureairportId = airports.ID INNER JOIN airports airports_2 ON flights.arrivalairportId = airports_2.ID INNER JOIN bookings where bookings.user_ID=? and bookings.flight_ID = flights.ID";
        	PreparedStatement statement = conn.prepareStatement(sql);
			statement.setInt(1, FlightBooking.currentUser.getUserId());

            ResultSet result = statement.executeQuery();
            while (result.next()) {
				Booking booking = new Booking(
						result.getInt("ID"),
						result.getInt("depatureairportId"),
						result.getInt("arrivalairportId"),
                        result.getTimestamp("tod"),
                        result.getDouble("price"),
                        result.getString("Depature_City"),
                        result.getString("Arrival_City")
                        );
						
                vec.add(booking);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return vec;
    }
    
    public void actionPerformed(ActionEvent event) {
    	Booking booking;
    	BookingDialog ad;
        int row;
        String ac = event.getActionCommand();
        switch (ac) {
        case ADD:
        	ad = new BookingDialog(this);
            ad.setVisible(true);
            booking = ad.getBooking();
            if (booking == null) // Canel har tryckts
                return;
            if (booking.dbInsert())
            	bookingModel.setBookings(loadBookings());
            break;
        case UPDATE:
        	row = table.getSelectedRow();
            if (row == -1) // Ingen rad vald
                return;
            booking = bookingModel.getBooking(row);
            ad = new BookingDialog(this, booking);
            ad.setVisible(true);
            booking = ad.getBooking();
            if (booking == null) // Canel har tryckts
                return;
//            if (booking.dbUpdate())
//            	bookingModel.setBookings(loadBookings());
//            break;
        case REMOVE:
            row = table.getSelectedRow();
            if (row == -1) // Ingen rad vald
                return;
            booking = bookingModel.getBooking(row);
            if (booking.dbDelete())
            	bookingModel.setBookings(loadBookings());
            break;
            }
        }
    }
   

/*------------------------------------------------------------------
 * Modell f������r tabellinneh������ll
 */
class BookingModel extends AbstractTableModel {
	
	
    private Vector<Booking> data = new Vector<Booking>();
    
    public void setBookings(Vector<Booking> bookings) {
    	data = bookings;
    	fireTableDataChanged();
    }
    
    public void addBooking(Booking booking) {
        data.addElement(booking);
        fireTableDataChanged();
    }
    public void removeRow(int row) {
        data.remove(row);
        fireTableDataChanged();
    }
    public Booking getBooking(int row) {
        return data.get(row);
    }
    public int getColumnCount() {
        return 5;
    }
    public int getRowCount() {
        return data.size();
    }
    public String getColumnName(int col) {
        switch (col) {
        case 0:
            return "Id";
        case 1:
            return "Depature City";
        case 2:
            return "Arrival City";
        case 3:
            return "Time of Depature";
        case 4:
            return "Price";
        case 5:
//            return "User id";
//        case 6:
//            return "Flight id";
        }
        return "";
    }
    public Object getValueAt(int row, int col) {
    	Booking booking = data.get(row);
        switch (col) {
        case 0:
            return booking.getFlightId();
        case 1:
            return booking.getDepature_City();
        case 2:
            return booking.getArrival_City();
        case 3:
        	return booking.getTod();
        case 4:
        	return booking.getFlightPrice();
//        case 5:
//        	return booking.getUser_ID();
//        case 6:
//        	return booking.getFlight_ID();
        }
        return "Unknown";
    }
    public Class<?> getColumnClass(int col) {
        switch (col) {
        case 0:
            return Integer.class;
        case 1:
            return Integer.class;
        case 2:
            return Integer.class;
        case 3:
            return Timestamp.class;
        case 4:
            return Double.class;
//        case 5:
//        	return Integer.class;
//        case 6:
//        	return Integer.class;
        }
        return Object.class;
    }
    public boolean isCellEditable(int row, int col) {
        return false;
    }
}
